package com.huanzhidadi.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanzhidadi.springsecurity.mapper.MenuMapper;
import com.huanzhidadi.springsecurity.mapper.UserMapper;
import com.huanzhidadi.springsecurity.model.LoginUser;
import com.huanzhidadi.springsecurity.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 根据用户名查询用户信息，供WebSecurityConfig的authenticationProvider()调用
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            log.error("访问失败，username：" + username + "不存在。");
            throw new UsernameNotFoundException("访问失败，用户名：" + username + "不存在。");
        }

        // TODO 查询对应的权限信息
        // List<String> list = new ArrayList<>(Arrays.asList("test", "admin"));
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setPermissions(list);
        return loginUser;
    }
}
